import { Component, Vue, Inject, Prop, Watch, Ref } from 'vue-property-decorator';
import { numeric, required, minLength, maxLength } from 'vuelidate/lib/validators';
import moment from 'moment';

import CommonTableFieldService from '../../modelConfig/common-table-field/common-table-field.service';
import { ICommonTableField } from '@/shared/model/modelConfig/common-table-field.model';

import CommonTableRelationshipService from '../../modelConfig/common-table-relationship/common-table-relationship.service';
import { ICommonTableRelationship } from '@/shared/model/modelConfig/common-table-relationship.model';

import UserService from '@/shared/service/user.service';

import BusinessTypeService from '../../settings/business-type/business-type.service';
import { IBusinessType } from '@/shared/model/settings/business-type.model';

import { ICommonTable, CommonTable } from '@/shared/model/modelConfig/common-table.model';
import CommonTableService from './common-table.service';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import { quillEditor } from 'vue-quill-editor';
import { UPLOAD_IMAGE_URL } from '@/constants';
import CommonTableFieldComponent from '../../modelConfig//common-table-field/common-table-field.vue';
import CommonTableRelationshipComponent from '../../modelConfig//common-table-relationship/common-table-relationship.vue';
import lowerFirst from 'lodash/lowerFirst';
import { generateDataForDesigner } from '@/utils/entity-form-utils';
import { idObjectArrayToIdArray, idsToIdObjectArray, getDataByFormField } from '@/utils/entity-utils';

const validations: any = {
  commonTable: {
    id: {},
    name: {
      required,
      maxLength: maxLength(80),
    },
    entityName: {
      required,
      maxLength: maxLength(80),
    },
    tableName: {
      required,
      maxLength: maxLength(80),
    },
    system: {},
    clazzName: {
      required,
      maxLength: maxLength(80),
    },
    generated: {},
    creatAt: {},
    generateAt: {},
    generateClassAt: {},
    description: {
      maxLength: maxLength(200),
    },
    treeTable: {},
    baseTableId: {},
    recordActionWidth: {},
    listConfig: {},
    formConfig: {},
    editInModal: {},
    searchForm: {},
  },
};

@Component({
  validations,
  components: {
    'jhi-quill-editor': quillEditor,
    'jhi-common-table-field': CommonTableFieldComponent,
    'jhi-common-table-relationship': CommonTableRelationshipComponent,
  },
})
export default class CommonTableUpdate extends Vue {
  // jhipster-pro-please-regenerate-this-file 如果您修改了此文件，并且不希望重新生成代码时被覆盖，请删除本行！！!

  @Inject('commonTableService') private commonTableService: () => CommonTableService;
  public commonTable: ICommonTable = new CommonTable();

  @Inject('commonTableFieldService') private commonTableFieldService: () => CommonTableFieldService;

  public commonTableFields: ICommonTableField[] = [];

  @Inject('commonTableRelationshipService') private commonTableRelationshipService: () => CommonTableRelationshipService;

  public commonTableRelationships: ICommonTableRelationship[] = [];

  public commonTables: ICommonTable[] = [];

  @Inject('userService') private userService: () => UserService;

  public users: Array<any> = [];

  @Inject('businessTypeService') private businessTypeService: () => BusinessTypeService;

  public businessTypes: IBusinessType[] = [];
  public isSaving = false;
  public loading = false;
  @Ref('updateForm') readonly updateForm: any;
  public formJsonData = {
    list: [],
    config: {
      layout: 'horizontal',
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      hideRequiredMark: false,
      customStyle: '',
    },
  };
  public relationshipsData: any = {};
  public dataFormContent = [];
  @Prop(Number) updateEntityId;
  @Prop(Boolean) showInModal;
  public dataContent = [];
  public commonTableId = null;

  created(): void {
    // 判断是否从路由中获得实体id
    if (this.$route.params.commonTableId) {
      this.commonTableId = this.$route.params.commonTableId;
    }
    this.initRelationships();
  }

  public mounted(): void {}

  public save(): void {
    this.isSaving = true;
    const that = this;
    this.updateForm
      .getData()
      .then(values => {
        Object.assign(that.commonTable, values);
        if (that.commonTable.id) {
          this.commonTableService()
            .update(that.commonTable)
            .then(param => {
              that.isSaving = false;
              const message = this.$t('jhipsterApp.modelConfigCommonTable.updated', { param: param.id }).toString();
              this.$message.info(message);
              this.$router.go(-1);
            });
        } else {
          this.commonTableService()
            .create(this.commonTable)
            .then(param => {
              that.isSaving = false;
              const message = this.$t('jhipsterApp.modelConfigCommonTable.created', { param: param.id }).toString();
              this.$message.success(message);
              this.$router.go(-1);
            });
        }
      })
      .catch(err => {
        this.$message.error('数据变更失败！');
        console.log(err);
      });
  }

  public retrieveCommonTable(commonTableId): void {
    if (!commonTableId) {
      return;
    }
    this.commonTableService()
      .find(commonTableId)
      .then(res => {
        this.commonTable = res;
        this.getFormData();
      });
  }

  public previousState(): void {
    this.$router.go(-1);
  }

  public initRelationships(): void {
    this.loading = true;
    Promise.all([this.commonTableService().retrieve(), this.userService().retrieve(), this.businessTypeService().retrieve()])
      .then(([commonTablesRes, usersRes, businessTypesRes]) => {
        this.relationshipsData['commonTables'] = commonTablesRes.data;
        this.relationshipsData['users'] = usersRes.data;
        this.relationshipsData['businessTypes'] = businessTypesRes.data;
        this.relationshipsData['entity'] = this.commonTable;
        this.getData();
      })
      .catch(error => {
        this.loading = false;
        this.$message.error({
          content: `数据获取失败`,
          onClose: () => {
            this.getData();
          },
        });
      });
  }
  public getData() {
    if (this.commonTableId || this.updateEntityId) {
      this.retrieveCommonTable(this.commonTableId || this.updateEntityId);
    } else {
      this.getFormData();
    }
  }
  public getFormData(formDataId?: number) {
    if (formDataId) {
      this.commonTableService()
        .find(formDataId)
        .then(res => {
          this.updateFormData(res);
        });
    } else {
      this.commonTableService()
        .findByEntityName('CommonTable')
        .then(res => {
          this.updateFormData(res);
        });
    }
  }
  private updateFormData(res: any) {
    const commonTableData = res;
    if (commonTableData.formConfig && commonTableData.formConfig.length > 0) {
      this.formJsonData = JSON.parse(commonTableData.formConfig);
    } else {
      this.formJsonData.list = generateDataForDesigner(commonTableData);
    }
    if (this.formJsonData.list) {
      this.formJsonData.list.forEach(item => {
        if (item.type === 'modalSelect' && this.commonTable[item.key]) {
          const isArray = Array.isArray(this.commonTable[item.key]);
          const options = {};
          const propertyName = isArray ? 'id.in' : 'id.equals';
          // options[propertyName] = this.commonTable[item.key];
          if (isArray) {
            if (this.relationshipsData[item.options.dynamicKey]) {
              if (this.commonTable[item.key]) {
                const findIds = this.commonTable[item.key].filter(idItem => {
                  return !this.relationshipsData[item.options.dynamicKey].some(dataItem => dataItem.id === idItem);
                });
                if (findIds.length > 0) {
                  options[propertyName] = findIds;
                }
              }
            }
          } else {
            if (this.commonTable[item.key]) {
              if (!this.relationshipsData[item.options.dynamicKey].some(dataItem => dataItem.id === this.commonTable[item.key])) {
                options[propertyName] = this.commonTable[item.key];
              }
            }
          }
          if (options[propertyName]) {
            this[lowerFirst(item.commonTableName + 'Service')]
              .call(this)
              .retrieve(options)
              .then(res => {
                const newData = this.relationshipsData[item.options.dynamicKey].concat(res.data);
                delete this.relationshipsData[item.options.dynamicKey];
                this.$set(this.relationshipsData, item.options.dynamicKey, newData);
              });
          }
        }
      });
    }
    this.relationshipsData['entity'] = this.commonTable;
    this.$nextTick(() => {
      this.updateForm.setData(getDataByFormField(this.formJsonData.list, this.commonTable)); // loadsh的pick方法
    });
  }
}
